<template>
  <div class="article-list">
    <van-pull-refresh v-model="isLoading" animation-duration="1000" success-duration="1000" :success-text="refreshSuccessText" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" :error.sync="error" error-text="请求失败，点击重新加载" @load="onLoad">
        <ArticleItem v-for="(item,index) in list" :key="index" :article="item" />
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/article-item'
import { getArticles } from '@/api/home'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channels: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      error: false, // 是否加载失败
      timestamp: null, // 请求下一页数据的时间戳
      isLoading: false,
      refreshSuccessText: ''
    }
  },
  computed: {},
  watch: {},
  created () {
    // console.log(this.channels)
  },
  mounted () {},
  methods: {
    async onLoad () {
    //   console.log(1)
      // 1. 请求获取数据
    //   console.log(this.channels)
      try {
        const { data: { data } } = await getArticles({
          channel_id: this.channels.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        const { results } = data
        // console.log(results)
        this.list = [...this.list, ...results]
        // console.log(this.list)
        this.loading = false
        if (results.length) {
          this.timestamp = data.pre_timestamp
          // console.log(2)
        } else {
          // 没有数据了，设置加载状态结束，不再触发上拉加载更多了
          this.finished = true
        }
      } catch (error) {
        console.log(error)
        this.loading = false // 关闭 loading 效果
        this.error = true // 开启错误提示
      }
    },
    async onRefresh () {
      try {
        const { data: { data } } = await getArticles({
          channel_id: this.channels.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        const { results } = data
        console.log(results)
        this.list = [...this.list, ...results]
        this.isLoading = false
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
      } catch (error) {
        console.log(error)
        this.isLoading = false // 关闭下拉刷新的 loading 状态
        this.$toast('刷新失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.artcile-list {
  height: 79vh;
  overflow: auto;
}
</style>
